package cmd

import (
	"gitee.com/feimos/dm/core"
	"gitee.com/feimos/dm/utils"
	"github.com/urfave/cli/v2"
	"log"
	"os"
	"path/filepath"
)

// FindCommand 处理 find subcommand
func FindCommand(c *cli.Context) error {

	name := core.UnifyPath(c.Args().First())
	root, err := filepath.Abs(filepath.Dir(os.Args[0]))

	if err != nil {
		return err
	}

	yamlContent, err := core.LoadYaml(root)

	if err != nil {
		log.Println(err)
		log.Fatalln("try to use \"dm init\" to generate config file")
	}

	count := c.Int("count")
	timeSort := c.Int("time")
	sizeSort := c.Int("size")

	ignoreCase := c.Bool("ignore-case")

	if count <= 0 {
		log.Printf("find flag \"count\" with value %v and it will be seen as 0\n", count)
	}

	findList := core.FindDocument(yamlContent, name, ignoreCase)

	documentList := core.FilterFindList(findList, count, timeSort, sizeSort)

	utils.PrintSearchResult(documentList)

	return nil
}
